package com.socket.nio.nio.sticky.fixedlength;

import cn.hutool.core.util.StrUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.CharsetUtil;

/**
 * 固定长度解码器 客户端
 *
 * @author Hexudong
 * @date 2025/5/5
 */
public class FixedLengthClient {

  private final String host;

  private final int port;

  public FixedLengthClient(String host, int port) {
    this.host = host;
    this.port = port;
  }

  public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();

    try {
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioSocketChannel.class)
          .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
              // 添加固定长度解码器
              ch.pipeline().addLast(new FixedLengthFrameDecoder(10));
              // 将ByteBuf转换为String
              ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
              // 业务处理器
              ch.pipeline().addLast(new FixedLengthClientHandler());
            }
          });
      ChannelFuture channelFuture = b.connect(this.host, this.port).sync();

      Channel channel = channelFuture.channel();
      sendFixedLengthMessage(channel, "Hello");
      sendFixedLengthMessage(channel, "Netty");
      sendFixedLengthMessage(channel, "Fixed");
      sendFixedLengthMessage(channel, "Length");

      channel.closeFuture().sync();
    } finally {
      group.shutdownGracefully();
    }
  }

  /**
   * 发送固定长度的消息
   *
   * @param channel 渠道
   * @param msg 消息
   */
  private void sendFixedLengthMessage(Channel channel, String msg) {
    String formattedMsg = StrUtil.padAfter(msg, 10, "-");
    channel.writeAndFlush(Unpooled.copiedBuffer(formattedMsg, CharsetUtil.UTF_8));
  }

  public static void main(String[] args) throws Exception {
    new FixedLengthClient("localhost", 8082).run();
  }
}
